--- title: Static Plots keywords: fastai sidebar: home_sidebar summary: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." description: "All types of plots in matplotlib are included in this module. This includes bands,DOS and other general plots, which can be saved as pdf,png,jpg and other formats that matplotlib offers." nb_path: "StaticPlots.ipynb" ---
{% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 

{% endraw %}

Passing Large Number of Arguments as a Dictionary

  • Let's take example of plot_bands. It requires 10 arguments and most of them are default, but in order to tweak parameters, you still need to access them. Follow These steps to input arguments easily.
  • In code cell, write plot_bands? and hit enter. This will give Signature and DocString.
  • Copy arguments and pass to a dictionary dict(what you copied). In a Jupyter Notebook cell, you can edit it:
{% raw %}
arg_dict=dict(
    ax=None,
    kpath=None,
    bands=None,
    showlegend=True,
    E_Fermi=0,
    color1=(1, 0, 0.8),
    style1='solid',
    lw1=0.7,
    )
arg_dict
{'ax': None,
 'kpath': None,
 'bands': None,
 'showlegend': True,
 'E_Fermi': 0,
 'color1': (1, 0, 0.8),
 'style1': 'solid',
 'lw1': 0.7}
{% endraw %}
  • As you can see, I deleted few unnecessary arguments. Now you can use dictionary unpacking operator ** inside function, it will pass all arguments present in dictionary. Make sure you do not change name of variables, although you can delete as few of them.
  • Usage: Call function as plot_bands(**arg_dict). You can edit dictionary on fly, or can save it to a file to read (Not recommended, could be a threat to your system security as reading dictionaries from a file could run potentially harmful commands as well.)

Simple Band Struture Plots

{% raw %}

plot_bands[source]

plot_bands(ax=None, kpath=None, bands=None, showlegend=False, E_Fermi=None, color1=(0, 0, 0.8), style1='solid', lw1=0.7, color2=(0.8, 0, 0), style2='dashed', lw2=0.7)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • ax : Matplotlib axes object, if not given, one is created.
    • kpath : 1D array from get_kpts().kpath or export_vasprun().kpath.
    • bands : Dictionary Object from get_evals or export_vasprun().bands.
    • showlegend : Boolean, default is False, if true, gives legend for spin-polarized calculations.
    • E_Fermi : If not given, automatically picked from bands object.
    • **kwargs : lines color,width and style to distinguish spin Up and Down.
  • Returns
    • ax : matplotlib axes object with plotted bands.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

modify_axes[source]

modify_axes(ax=None, xticks=[], xt_labels=[], xlim=[], yticks=[], yt_labels=[], ylim=[], xlabel=None, ylabel=None, vlines=True, zeroline=True)

  • Returns None, applies given settings on axes. Prefered to use before other plotting.
  • Parameters
    • ax : Matplotlib axes object.
    • (x,y)ticks : List of positions on (x,y axes).
    • (xt,yt)_labels : List of labels on (x,y) ticks points.
    • (x,y)lim : [min, max] of (x,y) axes.
    • (x,y)label : axes labels.
    • vlines : If true, drawn when ylim is not empty.
    • zeroline : If True, drawn when xlim is not empty.
{% endraw %} {% raw %}
{% endraw %}

Working in object-oriented way, we can have plenty of options in matplotlib. See the example below, which provides an overview of flexibility of matplotlib. All functions are defined in object-oriented way for better compatibility and flexibility.

Example: Graphene

{% raw %}
import pivotpy.vr_parser as vp
vr1=vp.export_vasprun(path=f1)
vr2=vp.export_vasprun(path=f2)
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt

fig,ax=plt.subplots(1,3,figsize=(10.2,2.6),sharey=True)
ax0=sp.plot_bands(ax=ax[0],kpath=vr2.kpath,bands=vr2.bands,showlegend=True)

ax1=sp.plot_bands(ax=ax[1],kpath=vr1.kpath,bands=vr1.bands,color1='y')

ax2=sp.plot_bands(ax=ax[2],kpath=vr1.kpath,bands=vr1.bands,color1='y')
ax2=sp.plot_bands(ax=ax[2],kpath=vr2.kpath,bands=vr2.bands,showlegend=True)
xticks=[vr1.kpath[i] for i in [0,30,60,-1]]
txts=["Polarized","Unpolarized","Comparison"]
for axes,txt in zip(ax,txts):
    if axes==ax0:
        sp.modify_axes(ax=axes,ylabel='Energy (eV)')
    sp.modify_axes(ax=axes,ylim=[-10,10],xlim=[xticks[0],xticks[-1]],xticks=xticks,xt_labels=[r'$\Gamma$','M','K',r'$\Gamma$'])
    axes.text(0.05,0.9,txt,bbox=dict(edgecolor='white',facecolor='white', alpha=0.9),transform=axes.transAxes,color='red')
plt.subplots_adjust(hspace=0.01,wspace=0.05)
{% endraw %} {% raw %}

quick_bplot[source]

quick_bplot(path_evr=None, ax=None, skipk=None, joinPathAt=[], elim=[], xt_indices=[], xt_labels=[], E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.9], ctxt='black')

  • Returns axes object and plot on which all matplotlib allowed actions could be performed.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • **kwargs : figsize=(3.4,2.6). Text,its position and color.
  • Returns
    • ax : matplotlib axes object with plotted bands.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

add_text[source]

add_text(ax=None, xs=0.05, ys=0.9, txts='[List]', colors='r')

  • Adds text entries on axes, given single string or list.
  • Parameters
    • xs : List of x coordinates relative to axes or single coordinate.
    • ys : List of y coordinates relative to axes or single coordinate.
    • txts : List of strings or one string.
    • colors: List of x colors of txts or one color.
{% endraw %} {% raw %}
{% endraw %}

Below is example where you can add multiple text entries on a quick_bplot.

{% raw %}
ax=sp.quick_bplot(path_evr=f2,elim=[-5,5],xt_indices=[0,30,60,-1],xt_labels=['W','K',''],txt='Graphene',ctxt='r')
sp.add_text(ax=ax,xs=[0.35,0.5],ys=[0.55,0.7],txts=[r'$E_{gap}$ = 0 eV','edge states'],colors=['red','blue'])
{% endraw %} {% raw %}

add_legend[source]

add_legend(ax=None, colors=[], labels=[], styles='solid', widths=0.7, anchor=(0, 1), ncol=3, loc='lower left', fontsize='small', frameon=False, **legend_kwargs)

  • Adds custom legeneds on a given axes,returns None.
  • Parameters
    • ax : Matplotlib axes.
    • colors : List of colors.
    • labels : List of labels.
    • styles : str or list of line styles.
    • widths : str or list of line widths.
    • **kwargs : Matplotlib's legend arguments.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

add_colorbar[source]

add_colorbar(ax=None, cmap_or_clist=None, N=256, ticks=[0.16666666666666666, 0.5, 0.8333333333333334], ticklabels=['r', 'g', 'b'], vertical=False, fontsize=8)

  • Plots colorbar on a given axes. This axes should be only for colorbar. Returns None or throws ValueError for given colors.
  • Parameters
    • ax : Matplotlib axes object.
    • cmap_or_clist: List/array of colors in or colormap's name. If None(default), first tries to get latest quick_rgb_lines colormap and if no success, then RGB_f colorbar is added. If nothing works, matplotlib's default colormap is plotted.
    • N : int, number of color points Default 256.
    • ticks : List of tick values to show on colorbar in interval [0,1].
    • ticklabels : List of labels for ticks.
    • vertical : Boolean, default is Fasle.
    • fontsize : Default 8. Adjustable according to plot space.
  • Note: Use 'RGB_f' to map colors (after) plotted in quick_rgb_lines and use 'RGB_m' to plot DOS in same colors.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy.s_plots as sp
import matplotlib.pyplot as plt 
plt.style.use('default')
fig,ax=plt.subplots(1,2,figsize=(9,1))
add_colorbar(ax[0],'RGB',vertical=True,N=7)
add_colorbar(ax=ax[1],cmap_or_clist=['r','g','b',2],N=21)
Invalid RGBA argument: 2 
Falling back to default color map!
{% endraw %} {% raw %}

color_wheel[source]

color_wheel(ax=None, xy=(1, 1), scale=0.12, rlim=(0.2, 1), N=256, color_map=None, ticks=[0.16666666666666666, 0.5, 0.8333333333333334], labels=['s', 'p', 'd'], showlegend=True)

  • Returns cax i.e. color wheel axes.
  • Parameters
    • ax : Axes on which color wheel will be drawn. Auto created if not given.
    • xy : (x,y) of center of wheel.
    • scale : Scale of the cax internally generated by color wheel.
    • rlim : Values in [0,1] interval, to make donut like shape.
    • N : Number of segments in color wheel.
    • color_map : Matplotlib's color map name. Auto picks RGB_f and if fails, fallbacks to viridis.
    • ticks : Ticks in fractions in interval [0,1].
    • labels : Ticks labels.
    • showlegend: True or False.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
color_wheel(xy=(0.5,0.5),scale=0.5,color_map='hsv',ticks=[0,1/3,2/3],labels=['Red','Green','Blue'])
<matplotlib.projections.polar.PolarAxes at 0x19ee2822c88>
{% endraw %}

Including Atomic and Orbital Projections

{% raw %}

get_pros_data[source]

get_pros_data(kpath=None, evals_set=None, pros_set=None, elements=[[0]], orbs=[[0]], interpolate=False, scale_data=False, n=5, k=3)

  • Returns selected elements/orbitals data.
  • Parameters
    • kapath : export_vasprun().kpath or get_kpts().kpath.
    • evals_set: export_vasprun().bands.evals or get_evals().evals. If calculations are spin-polarized, it will be ...evals.SpinUp/SpinDown for both.
    • pros_set : export_vasprun().pro_bands.pros or get_bands_pro_set().pros. If calculations are spin-polarized, it will be ...pros.SpinUp/SpinDown for both.
    • elements : Lists of list of ions to project on, could be range(start,stop,step) as well, remember that stop is not included in python. so range(0,2) will generate 0 and 1 indices.
    • orbs : List of lists of orbitals indices.
    • scale_data : If True, normalizes projection data to 1.
    • interpolate: Deafult is false, if True, it will add n points between nearest kpoints.
    • n : int, default is 5. Adds n points between nearest kpoints.
    • k : int, order of interpolation, defualt is 3. n > k should be hold.
  • Returns
    • A dictionary with keys 'kpath', 'evals', 'colors' that can be unpacked in next function's arguemnet.
      • 'kpath' : Given or interpolated kpath of shape (NKPTS,).
      • 'evals' : Given or interpolated evals_set of shape (NKPTS,NBANDS).
      • 'pros': An array of shape (NKPTS,NBANDS,n) where n is length of input elements list. If scale_data = True, normalizes this array to 1.
{% endraw %} {% raw %}

make_line_collection[source]

make_line_collection(max_width=None, colors_list=None, rgb=False, uni_width=False, scale_color=False, **pros_data)

  • Returns a tuple of line collections. If rgb = True (at len(orbs) = 3 in get_pros_data), returns a tuple of two entries, multicolored line collection and RGB maximum values, otherwise return tuple of single colored multiple lines.
  • Parametrs
    • **pros_data: Output dictionary from get_pros_data containing kpath, evals and colors arrays.
    • max_width : Default is None and max linwidth = 2.5. Max inewidth is scaled to max_width if an int of float is given.
    • colors_list: List of colors for multiple lines, length equal to 3rd axis length of colors.
    • rgb : Default is False. If True and np.shape(colors)[-1] == 3, RGB line collection is returned in a tuple of length 1. Tuple is just to support iteration.
    • uni_width : Default is False, If True, makes linewidth uniform at width = max_width/2.
    • scale_color: If True, normalizes each point's color value, as (0,0,0.5) --> (0,0,1). If False, clips colors in range [0,1] but does not effect linewidth.
{% endraw %} {% raw %}

plot_collection[source]

plot_collection(gpd_args, mlc_args, axes=None)

  • Plots line collection from the output of get_pros_data and make_line_collection on axes.
  • Parameters
    • gpd_args: Dictionary of arguments from function get_pros_data. Do not unpack it.
    • mlc_args: Dictionary of arguments from function make_line_collection. Do not unpack it.
    • axes : A single or list of matplotlib's Axes. len(list) should be equal to len(orbs) given in get_pros_data. If axes = None, auto generated.
  • Returns
    • axes: axes to return are spacially useful when axes = None, you can perform other actions on those axes. It will be a list of axes and all items could be same, depending on whether one are many axes were given/generated.
{% endraw %} {% raw %}
{% endraw %}
{% raw %}
import time
start=time.time()
import numpy as np 
import pivotpy as pp
vr = pp.export_vasprun('E:/Research/graphene_example/ISPIN_2/bands/vasprun.xml',elim=[-10,10])
k=vr.kpath
ef=vr.tdos.E_Fermi
en=vr.bands.evals.SpinUp-ef
pros=vr.pro_bands.pros.SpinUp
gpd_args = dict(kpath=k,evals_set=en,pros_set=pros,scale_data=True)
mlc_args = dict(max_width = 2.5,colors_list = None,rgb = False,uni_width = False, scale_color = False)
Loading from PowerShell Exported Data...
{% endraw %} {% raw %}
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt 
plt.style.use('seaborn')
axs = sp.init_figure(ncols=3,figsize=(8,2.6),sharey=True)
axc = axs[0].get_figure().add_axes([0.5,1,0.3,0.04])

gpd_args.update(elements=[[0,1],[0,1],[0,1]],orbs=[[0],[2],[1,3]])
mlc_args['colors_list'] = [(1,0,0,1),(0,1,0,1),(0,0,1,0.4)]
plot_collection(gpd_args,mlc_args,axes=axs[0])
sp.add_legend(ax=axs[0],labels=['C-s','C-pz','C-px+py'],widths=2.5,colors=mlc_args['colors_list'])

gpd_args['orbs'] = [[0],[1,2,3],[4,5,6,7,8]]
plot_collection(gpd_args,mlc_args,axes=axs[1])

mlc_args['uni_width'] = True
plot_collection(gpd_args,mlc_args,axes=axs[2])

_ = [sp.modify_axes(ax=ax) for ax in axs]
sp.add_colorbar(ax=axc,cmap_or_clist = mlc_args['colors_list'],ticklabels=['C-s','C-p','C-d'],ticks=[0,0.5,1])
plt.subplots_adjust(wspace=0.05)
txts=['Default/s,pz,px+py','uni_width=False/s,p,d','uni_width=True/s,p,d']
_ = [sp.add_text(ax=ax,txts=txt) for ax,txt in zip(axs,txts)]
print('Executed in {} seconds.'.format(time.time()-start))
Executed in 1.673912525177002 seconds.
{% endraw %}
{% raw %}

quick_rgb_lines[source]

quick_rgb_lines(path_evr=None, ax=None, skipk=None, joinPathAt=[], elim=[], elements=[[0], [], []], orbs=[[0], [], []], labels=['Elem0-s', '', ''], max_width=None, xt_indices=[0, -1], xt_labels=['$\\Gamma$', 'M'], E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.9], ctxt='black', uni_width=False, interpolate=False, spin='both', n=5, k=3, scale_color=True, scale_data=True, colorbar=True, color_matrix=None)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. In this function,orbs,labels,elements all have list of length 3. Inside list, sublists or strings could be any length but should be there even if empty.
  • Parameters
    • path_evr : path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if not given, one is created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • elements : List [[0],[],[]] by default and plots s orbital of first ion..
    • orbs : List [[r],[g],[b]] of indices of orbitals, could be empty, but shape should be same.
    • labels : List [str,str,str] of projection labels. empty string should exist to maintain shape. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in colorbar ticks or legend.
    • max_width : Width to scale whole projections. if uni_width=True, width=max_width/2. Default is None and linewidth at any point = 2.5*sum(ions+orbitals projection of all three input at that point). Linewidth is scaled to max_width if an int or float is given.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • uni_width : If True, width of bands kept uniform.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • scale_color: Boolean. Default True, colors are scaled to 1 at each point. If False, clips colors in range [0,1] but does not effect linewidth.
    • scale_data : Default is True and normalizes projection data to 1. Has no visual effect if scale_color = True too.
    • colorbar : Default is True. Displays a vertical RGB colorbar.
    • color_matrix: Only works if scale_color==True. 3x3 or 3x4 numpy array or list to transform from RGB to another space,provided that sum(color_matrix[i,:3]) <= 1. 4th column, if given can be used to control the saturation,contrast and brightness as s,c,b = color_matrix[:,3] For simply changing the color intensity use np.diag([r,g,b]) with r,g,b interval in [0,1]. Try pivotpy.color_matrix as suggested color matrix and modify, which at s=0 returns gray scale.!
  • Returns
    • ax : matplotlib axes object with plotted projected bands.
    • Registers as colormap RGB_m to use in DOS to plot in same colors and RGB_f to display bands colorbar on another axes.

      Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None, scale_color=False as these parameters act internally on data.

{% endraw %} {% raw %}
{% endraw %}
  • quick_rgb_lines() is waraper around make_line_collection(rgb=True). You can pass lists for orbs,labels, and elements each of length 3 which will be plotted on one axes.
    • If you do not provide any arguemnts, this will create graph of s orbital of first ion.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list(length=3) of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If scale_color=True, ecah point on plot is scaled to maximum color, if False, whole data is normalized if scale_data=True.
    • color_matrix is to convert between color spaces and play around as you can. Sum of each row up yo 3 columns should be less than or equal to 1. 4th column of color_matrix is for saturation, contrast and brightness from top to bottom in order. Only works if scale_color=True. {% include tip.html content='pivotpy.color_matrix and pivotpy.gray_matrix are 3x4 quick matrices.' %}{% include tip.html content='Use RGB_m for DOS and RGB_f for bands plotting in same color. RGB_f is auto-picked by add_colorbar.' %}
{% raw %}
import os
import numpy as np
os.chdir('E:/Research/graphene_example/ISPIN_2/bands')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pivotpy as pp
evr = pp.export_vasprun()
args_dict = dict(path_evr=evr,elements=[0,[0,1],[0,1]],orbs=[0,[1],[2,3]],labels=['s','p$_z$','p$_x$+p$_y$'])

axs=pp.init_figure(nrows=2,ncols=3,figsize=(9,5),sharex=True,sharey=True);
caxs = pp.init_figure(nrows=2,ncols=3,figsize=(9,1),sharex=True,sharey=True,top=0.5)
quick_rgb_lines(ax=axs[0,0],**args_dict,spin='up',txt='scale_color=False',scale_color=False)
pp.add_colorbar(caxs[0,0])
quick_rgb_lines(ax=axs[0,1],**args_dict,scale_data=False,scale_color=False,spin='down',txt='scale_[color,data]=False')
pp.add_colorbar(caxs[0,1])
quick_rgb_lines(ax=axs[0,2],**args_dict,spin='both',txt='scale_color=True')
pp.add_colorbar(caxs[0,2])

plt.style.use(['default','seaborn'])
_ = quick_rgb_lines(ax=axs[1,0],**args_dict,spin='up',txt='color_matrix',color_matrix=pp.color_matrix)
pp.add_colorbar(caxs[1,0])
_ = quick_rgb_lines(ax=axs[1,1],**args_dict,spin='down',txt='color_matrix.T',color_matrix=pp.color_matrix.T)
pp.add_colorbar(caxs[1,1])
_ = quick_rgb_lines(ax=axs[1,2],**args_dict,spin='both',txt='gray_matrix',color_matrix=pp.gray_matrix)
pp.add_colorbar(caxs[1,2])
caxs[0,0].get_figure().suptitle("These colorbars are dynamically generated in sequence to above figure's axes")
Loading from PowerShell Exported Data...
 elements[0] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
Text(0.5, 0.98, "These colorbars are dynamically generated in sequence to above figure's axes")
{% endraw %} {% raw %}

quick_color_lines[source]

quick_color_lines(path_evr=None, axes=None, skipk=None, joinPathAt=[], elim=[], elements=[[0]], orbs=[[0]], labels=['s'], color_map='gist_rainbow', scale_data=False, max_width=None, spin='both', xt_indices=[0, -1], xt_labels=['$\\Gamma$', 'M'], E_Fermi=None, showlegend=True, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.85], ctxt='black', interpolate=False, n=5, k=3, legend_kwargs={'ncol': 4, 'anchor': (0, 1.05), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': False}, **subplots_adjust_kwargs)

  • Returns axes object and plot on which all matplotlib allowed actions could be performed. If given, elements, orbs, and labels must have same length. If not given, zeroth ion is plotted with s-orbital.
  • Parameters
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • axes : Matplotlib axes object with one or many axes, if not given, auto created.
    • skipk : Number of kpoints to skip, default will be from IBZKPT.
    • joinPathAt : Points where kpath is broken.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • xt_indices : High symmetry kpoints indices.abs
    • xt_labels : High Symmetry kpoints labels.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2. If a label is empty i.e. '', it will not show up in legend.
    • color_map : Matplotlib's standard color maps. Default is 'gist_ranibow'.
    • showlegend : True by defualt and displays legend relative to axes[0]. If False, it writes text on individual ax.
    • scale_data : Default is False, If True, normalize projection data to 1.
    • max_width : Width to scale whole projections. Default is None and linewidth at any point on a line = 2.5*sum(ions+orbitals projection of the input for that line at that point). Linewidth is scaled to max_width if an int or float is given.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • legend_kwargs: Dictionary containing legend arguments.
    • **subplots_adjust_kwargs : plt.subplots_adjust parameters.
  • Returns
    • ax : matplotlib axes object with plotted projected bands.

      Note: Two figures made by this function could be comapred quantitatively only if scale_data=False, max_width=None as these parameters act internally on data.

{% endraw %} {% raw %}
{% endraw %}
  • quick_color_lines() is waraper around make_line_collection(rgb=False,uni_width=False,scale_color = False). You can pass equal length lists for orbs,labels, and elements either with one axis or mutltiple axes of same length as orbs.
    • If you do not provide any arguemnts, this will plots-orbital of first ion.
    • elements argument is special, you can pass index of element which will pick all ions of that type, or list of indices of ions, e.g in elements=[0,[0,1],2] of system Ga32As31Bi1, 0 and 2 pick all ions of Ga and Bi respectively, while [0,1] will pick first two ions of Ga.
    • If your given len(axis)=1, all projections are plotted on single axis and you can tweak plot aesthetics, legend display etc. There are plenty of options.
    • If a label is empty i.e. '', it will not show up in legend.

Colors Selection

Instead of giving custom colors, you can use matplotlib's colormaps to be consistent. Use

plt.colormaps()

to see list of available color maps. To get a color array from a map, you can do the following:

from matplotlib.pyplot import cm
colors  = cm.hsv(np.linspace(0,1,3))
# This will give you three colors from 'hsv' map.

Note: A custom colormaps RGB is registered in session when you import pivotpy, which could be used when plotting DOS with bands of same color. An additional colormap RGB_m a at any moment would represent the latest quick_rgb_lines run.

{% raw %}
import os
path='E:/Research/graphene_example/ISPIN_2/bands'
os.chdir(path)
import pivotpy 
import importlib as imp
pp = imp.reload(pivotpy)
import matplotlib.pyplot as plt
axs=pp.init_figure(nrows=1,ncols=3,figsize=(7,2.5),sharey=True,sharex=True)
args_dict=dict(elements=[0,0,[0,1]],orbs=[0,1,[2]],labels=['','$p_z$','$p_x$'],hspace=0.1,wspace=0.07,showlegend=True)
quick_color_lines(axes=axs[0],**args_dict,left=0.06,color_map='flag',spin='up');
quick_color_lines(axes=axs[1],**args_dict,left=0.06,color_map='FCC',spin='down',scale_data=True);
quick_color_lines(axes=axs[2],**args_dict,left=0.06,color_map='RGB',spin='both');
Loading from PowerShell Exported Data...
 elements[0] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
 elements[1] = 0 is converted to range(0, 2) which picks all ions of 'C'.To just pick one ion at this index, wrap it in brackets [].
Loading from PowerShell Exported Data...
color_map = 'FCC' not exists, falling back to default color map.
Loading from PowerShell Exported Data...
{% endraw %}

Initializing Figure

{% raw %}

init_figure[source]

init_figure(figsize=(3.4, 2.6), nrows=1, ncols=1, widths=[], heights=[], axes_off=[], sharex=False, sharey=False, **subplots_adjust_kwargs)

  • Returns flatten axes of initialized figure, based on plt.subplots(). If you want to access parent figure, use ax.get_figure() or current figure as plt.gcf().
  • Parameters
    • figsize : Tuple (width, height). Default is (3.4,2.6).
    • nrows : Default 1.
    • ncols : Default 1.
    • widths : List with len(widths)==nrows, to set width ratios of subplots.
    • heights : List with len(heights)==ncols, to set height ratios of subplots.
    • share(x,y): Share axes between plots, this removes shared ticks automatically.
    • axes_off : Turn off axes visibility, If nrows = ncols = 1, set True/False, If anyone of nrows or ncols > 1, provide list of axes indices to turn off. If both nrows and ncols > 1, provide list of tuples (x_index,y_index) of axes.
    • **subplots_adjust_kwargs : These are same as plt.subplots_adjust()'s arguements.
{% endraw %} {% raw %}
{% endraw %}

Tweaking init_figure by using gridspec.

  • This is a powerful way yo include any type of grid. For this, first use gs = axs[0,0].get_gridspec() and then remove axes you want to replace for another shape, then add required axis by plt.gcf().add_subplot(gs[x_ind, y_ind]). This process is illustrated in below examples.
  • Soft Tweaking
    • Axes remain same, just widths and height ratios are chnaged.
{% raw %}
import pivotpy.s_plots as sp 
axs = init_figure(figsize=(3.4,2.6),ncols=3,widths=[3.4,1,3.4],nrows=3,heights=[2.6,1,2.6],wspace=0.076,hspace=0.1)
[sp.modify_axes(ax=ax,xticks=[0],yticks=[0]) for ax in axs.ravel()]
[sp.add_colorbar(ax=ax,ticks=[]) for ax in [axs[1,0],axs[1,2]]];
_ = [sp.add_colorbar(ax=ax,vertical=True,ticks=[]) for ax in [axs[0,1],axs[2,1]]]
{% endraw %}
  • Brute Force Tweaking
    • Here we will remove and regenerate axes based on our grid choice.
{% raw %}
axs=init_figure(figsize=(5,3.4),nrows=3,ncols=2,widths=[1,1],heights=[1,7,7],wspace=0.4,hspace=0.4,axes_off=[(2,0)],sharex=True,sharey=True)
import pivotpy.s_plots as sp 
import matplotlib.pyplot as plt
gs = axs[0,0].get_gridspec()
axs_to_remove=[*axs[0, :],*axs[1:, 1]]
for ax in axs_to_remove:
    ax.remove()
axlarge = plt.gcf().add_subplot(gs[0, :])
axv = plt.gcf().add_subplot(gs[1:, 1])
sp.modify_axes(ax=axv)
sp.add_colorbar(ax=axlarge)
sp.add_text(ax=axs[1,0],txts='axis[1,0]',xs=0.25,ys=0.5)
sp.add_text(ax=axs[2,0],txts='axis[2,0] is off',xs=0.15,ys=0.5)
import pivotpy.vr_parser as vp 
vr=vp.export_vasprun(path='E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml')
sp.quick_bplot(path_evr=vr,ax=axv,txt='Plotting',E_Fermi=10)
sp.add_text(ax=axv,txts='BigAxes',xs=0.25,ys=0.5)
{% endraw %}
  • Mixing 2D and 3D axes in a figure
    • A minial example below shows deleting an axes and then adding a 3D axes with same dimensions.
{% raw %}
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt 
import pivotpy as pp 
ax = pp.init_figure(nrows=2,ncols=2,widths=[1,2],heights=[1,2])
pos = ax[1,1].get_position()
ax[1,1].remove()
ax[1,1]=plt.gcf().add_axes(pos,projection='3d')
{% endraw %}

Plotting Density of States

{% raw %}

select_pdos[source]

select_pdos(tdos=None, pdos_set=None, ions=[0], orbs=[0], E_Fermi=0, interpolate=False, n=5, k=3)

  • Returns (interpolated/orginal) enrgy(N,), tdos(N,), and pdos(N,) of selected ions/orbitals.
  • Parameters
    • tdos : export_vasprun().tdos or get_tdos().tdos. If calculations are spin-polarized, it will be ..tdos.SpinUp/SpinDown for both. You need to apply this function twice for SpinUp and SpinDown separately.
    • pdos_set : export_vasprun().pro_dos.pros or get_dos_pro_set().pros. If calculations are spin-polarized, it will be ...pros.SpinUp/SpinDown for both.
    • ions : List of ions to project on, could be range(start,stop,step) as well, remember that stop is not included in python. so range(0,2) will generate 0 and 1 indices.
    • orbs : List of orbitals indices to pick.
    • E_Fermi : Here it is zero. Needs to be input.
    • interpolate: Deafult is false, if True, it will add n points between nearest points.
    • n : int, default is 5. Adds n points between nearest kpoints.
    • k : int, order of interpolation, defualt is 3. n > k should be hold.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

collect_dos[source]

collect_dos(path_evr=None, elim=[], elements=[[0]], orbs=[[0]], labels=['s'], E_Fermi=None, spin='both', interpolate=False, n=5, k=3)

  • Returns lists of energy,tdos, pdos and labels. If given,elements,orbs and labels must have same length. If not given, zeroth ions is collected with s-orbital.
  • Parameters)
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
  • Returns
    • Energy : (N,1) size.
    • tdos : (N,1) size or [(N,1),(N,1)] if spin polarized.
    • pdos : [(N,1),(N,1),...], spin polarized is auto-fixed.
    • labels : ['label1,'label2',...] spin polarized is auto-fixed.
    • vr : Exported vasprun.
{% endraw %} {% raw %}
{% endraw %}
  • Providing labels while using collect_dos is important, it will automatically return spin up/down saymbols.
{% raw %}

quick_dos_lines[source]

quick_dos_lines(path_evr=None, ax=None, elim=[], include_dos='both', elements=[[0]], orbs=[[0]], labels=['s'], color_map='gist_rainbow', tdos_color=(0.8, 0.95, 0.8), linewidth=0.5, fill_area=True, vertical=False, E_Fermi=None, figsize=(3.4, 2.6), txt=None, xytxt=[0.05, 0.85], ctxt='black', spin='both', interpolate=False, n=5, k=3, showlegend=True, legend_kwargs={'ncol': 4, 'anchor': (0, 1), 'handletextpad': 0.5, 'handlelength': 1, 'fontsize': 'small', 'frameon': False})

  • Returns ax object (if ax!=False) and plot on which all matplotlib allowed actions could be performed, returns lists of energy,tdos and pdos and labels. If given,elements,orbs colors, and labels must have same length. If not given, zeroth ions is plotted with s-orbital.
  • Parameters)
    • path_evr : Path/to/vasprun.xml or output of export_vasprun. Auto picks in CWD.
    • ax : Matplotlib axes object, if None, one is created. If False, data lists are returned.
    • include_dos: One of {'both','tdos','pdos'}.
    • elim : [min,max] of energy range.
    • E_Fermi : If not given, automatically picked from export_vasprun.
    • elements : List [[0],], by defualt and plot first ion's projections.
    • orbs : List [[0],] lists of indices of orbitals, could be empty.
    • labels : List [str,] of orbitals labels. len(labels)==len(orbs) must hold. Auto adds , for ISPIN=2.
    • color_map : Matplotlib's standard color maps. Default is 'gist_ranibow'. Use 'RGB' if want to compare with quick_rgb_lines with 3 projection inputs (len(orbs)==3).
    • fill_area : Default is True and plots filled area for dos. If False, plots lines only.
    • vertical : False, If True, plots along y-axis.
    • showlegend : True by defualt.
    • figsize : Tuple (width,height) in inches. Default (3.4.2.6) is article column's width.
    • txt : Text on figure, if None, SYSTEM's name is printed.
    • xytxt : [x_coord,y_coord] of text relative to axes.
    • ctxt : color of text.
    • spin : Plot spin-polarized for spin {'up','down','both'}. Default is both.
    • interpolate: Default is False, if True, bands are interpolated.
    • n : int, number of points, default is 5.
    • k : int, order of interpolation 0,1,2,3. Defualt 3. n > k should be hold.
    • legend_kwargs: Dictionary to contain legend arguments to fix.
  • Returns
    • ax : Matplotlib axes.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
quick_dos_lines(path_evr='E:/Research/graphene_example/ISPIN_2/dos/vasprun.xml',vertical=False,fill_area=True,showlegend=True,include_dos='pdos',orbs=[[1,2,3],0,1],elements=[0,0,1],linewidth=1,labels=['p','s','g'],color_map='RGB',elim=[-5,5],spin='both')
<matplotlib.axes._subplots.AxesSubplot at 0x1d441494ec8>
{% endraw %}

High Display Image in Notebook

The function below plt_to_html is implemented for use in pivotpy-dash app to view and save SVG image directly from web app's interface. This also enables high display output in jupyter notebook.

{% raw %}

plt_to_html[source]

plt_to_html(plt_fig=None, transparent=True, dash_html=None)

  • Returns base64 encoded Image to display in notebook or HTML or plotly's dash_html_components.Img object.
  • Parameters
    • plt_fig : Matplotlib's figure instance, auto picks as well.
    • transparent: True of False for fig background.
    • dash_html : Default is None which results in an image display in jupyter notebook.
      • If True, returns html.Img object for plotly's dash.
      • If False, returns object to embed in HTML DOM.
{% endraw %} {% raw %}
{% endraw %} {% raw %}
import pivotpy as pp 
import matplotlib.pyplot as plt
pp.quick_bplot("E:/Research/graphene_example/ISPIN_1/bands/vasprun.xml",elim=[-9,9]);
fig = plt_to_html(dash_html=None,transparent=False)
fig
{% endraw %}

Below code snippest could be used to inclue svg in html document from a figure.

data = plt_to_html(dash_html=False)
html_str= """
<!DOCTYPE html>
<head></head>
<body>
    <div>
    {}
    </div>
</body>
""".format(data)

with open('fig.html','w') as f:
    f.write(html_str)
f.close()

LOCPOT/CHG Plot

{% raw %}

plot_potential[source]

plot_potential(basis=None, e_or_m=None, operation='mean_z', ax=None, period=None, lr_pos=(0.25, 0.75), lr_widths=[0.5, 0.5], labels=('$V(z)$', '$\\langle V \\rangle _{roll}(z)$', '$\\langle V \\rangle $'), colors=((0, 0.2, 0.7), 'b', 'r'), annotate=True)

  • Returns tuple(ax,Data) where Data contains resultatnt parameters of averaged potential of LOCPOT.
  • Parameters
    • basis : export_potential().basis.
    • e_or_m : epxort_potential().[e,m,m_x,m_y,m_z] is 3D grid data. As epxort_potential is slow, so compute it once and then plot the output data.
    • operation: Default is 'mean_z'. What to do with provided volumetric potential data. Anyone of these 'mean_x','min_x','max_x','mean_y','min_y','max_y','mean_z','min_z','max_z'.
    • ax: Matplotlib axes, if not given auto picks.
    • period: Periodicity of potential in fraction between 0 and 1. For example if a slab is made of 4 super cells in z-direction, period=0.25.
    • lr_pos: Locations around which averages are taken.Default (0.25,0.75). Provide in fraction between 0 and 1. Center of period is located at these given fractions. Work only if period is given.
    • lr_widths: Default is [0.5,0.5], you may have slabs which have different lengths on left and right side. Provide a pair proportional to widths e.g (1,1), (1,1.1) etc. and it is auto normalized to 1. Works only if period is given.
    • labels: List of three labels for legend. Use plt.legend() or pp.add_legend() for labels to appear. First entry is data plot, second is its convolution and third is complete average.
    • colors: List of three colors for lines.
    • annotate: True by default, writes difference of right and left averages on plot.
{% endraw %} {% raw %}
{% endraw %} {% raw %}

  Index 
  XmlElementTree 
  StaticPlots● 
  InteractivePlots 
  Utilities 
  StructureIO 
  Widgets 

{% endraw %}